/*!
 * Ext JS Library 4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */

/**
 * @class Ext.ux.desktop.Desktop
 * @extends Ext.panel.Panel
 *          <p>
 *          This class manages the wallpaper, shortcuts and taskbar.
 *          </p>
 */
Ext
		.define(
				'Ext.ux.desktop.Desktop',
				{
					extend : 'Ext.panel.Panel',

					alias : 'widget.desktop',

					uses : [ 'Ext.util.MixedCollection', 'Ext.menu.Menu',
							'Ext.view.View', // dataview
							'Ext.window.Window',

							'Ext.ux.desktop.TaskBar',
							'Ext.ux.desktop.Wallpaper' ],
					id : 'system_main_desktop',
					activeWindowCls : 'ux-desktop-active-win',
					inactiveWindowCls : 'ux-desktop-inactive-win',
					lastActiveWindow : null,

					border : false,
					html : '&#160;',
					layout : 'fit',

					xTickSize : 1,
					yTickSize : 1,

					app : null,

					/**
					 * @cfg {Array|Store} shortcuts The items to add to the
					 *      DataView. This can be a {@link Ext.data.Store Store}
					 *      or a simple array. Items should minimally provide
					 *      the fields in the
					 *      {@link Ext.ux.desktop.ShorcutModel ShortcutModel}.
					 */
					shortcuts : null,

					/**
					 * @cfg {String} shortcutItemSelector This property is
					 *      passed to the DataView for the desktop to select
					 *      shortcut items. If the {@link #shortcutTpl} is
					 *      modified, this will probably need to be modified as
					 *      well.
					 */
					shortcutItemSelector : 'div.ux-desktop-shortcut',

					/**
					 * @cfg {String} shortcutTpl This XTemplate is used to
					 *      render items in the DataView. If this is changed,
					 *      the {@link shortcutItemSelect} will probably also
					 *      need to changed.
					 */
					shortcutTpl : [
							/*
							 * '<tpl for=".">', '<div
							 * class="ux-desktop-shortcut" id="{id}-shortcut">', '<div>', // '<img
							 * src=" {vdtp}" title="{text}">', (!Ext.isIE6?'<img
							 * src=" {vdtp}" title="{text}">': '<div
							 * style="width:74px;height:74px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'{vdtp}\')"></div>'), '</div>', '<span
							 * class="ux-desktop-shortcut-text"><font
							 * color="#4D4D4D"><strong>{text}</strong></font></span>', '</div>', '</tpl>', '<div
							 * class="x-clear"></div>'
							 */
							'<tpl for=".">',
							'<div class="thumb-wrap">',
							'<div class="thumb">',
							(!Ext.isIE6 ? '<img src="{vdtp}"  title="{text}" />'
									: '<div style="width:74px;height:74px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'{vdtp}\')"></div>'),
							'</div>', '<span><strong>{text}</strong></span>',
							'</div>', '</tpl>' ],

					/**
					 * @cfg {Object} taskbarConfig The config object for the
					 *      TaskBar.
					 */
					taskbarConfig : null,

					windowMenu : null,

					initComponent : function() {
						var me = this;

						me.windowMenu = new Ext.menu.Menu(me.createWindowMenu());

						me.bbar = me.taskbar = new Ext.ux.desktop.TaskBar(
								me.taskbarConfig);
						me.taskbar.windowMenu = me.windowMenu;

						me.windows = new Ext.util.MixedCollection();

						me.contextMenu = new Ext.menu.Menu(me
								.createDesktopMenu());

						me.items = [ {
							xtype : 'wallpaper',
							id : me.id + '_wallpaper'
						}, me.createDataView() ];

						me.callParent();
						me.shortcutsView = me.items.getAt(1);
						me.shortcutsView.on('itemdblclick',
								me.onShortcutItemClick, me);
						/*
						 * me.shortcutsView .on( 'itemclick', function(dataView,
						 * record) { var record1 = me.shortcutsView
						 * .getSelectionModel() .getLastSelected(); if (record1) {
						 * document.getElementById(record1 .get('id') +
						 * '-shortcut').style.border = '';
						 * document.getElementById(record1 .get('id') +
						 * '-shortcut').style.backgroundColor = ''; }
						 * document.getElementById(record .get('id') +
						 * '-shortcut').style.border = '1px solid #CCC';
						 * document.getElementById(record .get('id') +
						 * '-shortcut').style.backgroundColor = '#E6F9F9'; },
						 * me);
						 */

						var dataViewMenu = new Ext.menu.Menu(
								{
									items : [
											{
												text : '运行',
												icon : '/hhcommon/images/icons/newspaper/newspaper_go.png',
												handler : function() {
													var record = me.shortcutsView
															.getSelectionModel()
															.getLastSelected();
													me.onShortcutItemClick(
															me.shortcutsView,
															record);
												}
											},
											{
												text : '外部运行',
												icon : '/hhcommon/images/icons/newspaper/newspaper_link.png',
												handler : function() {
													var record = me.shortcutsView
															.getSelectionModel()
															.getLastSelected();
													if (!Util.isNull(record)) {
														var data = record.data;
														var parmas = {};
														parmas.title = data.text;
														parmas.id = data.id;
														parmas.icon = data.icon;
														parmas.vsj = data.vsj;
														Util.openBrowser(parmas);
													} else {
														ExtFrame
																.info("请选中要删除快捷方式的菜单！");
													}
												}
											},
											{
												text : '删除',
												iconCls : 'delete',
												handler : function() {
													var record = me.shortcutsView
															.getSelectionModel()
															.getLastSelected();
													if (!Util.isNull(record)) {
														var resultObject = Request
																.synRequestObject(
																		'usersystem-menu-deleteZmtb',
																		{
																			id : record
																					.get("id")
																		});
														if (resultObject.success == true) {
															me.shortcuts
																	.remove(record);
														}
													} else {
														ExtFrame
																.info("请选中要删除快捷方式的菜单！");
													}
												}
											} ]
								});

						me.shortcutsView.on('itemcontextmenu', function(a, b,
								c, d, e) {
							c.click();
							dataViewMenu.showAt(e.getXY());
							dataViewMenu.doConstrain();
							e.stopEvent();
						}, me);

						var wallpaper = me.wallpaper;
						me.wallpaper = me.items.getAt(0);
						if (wallpaper) {
							me.setWallpaper(wallpaper, me.wallpaperStretch);
						}
					},

					afterRender : function() {
						var me = this;
						me.callParent();
						me.el.on('contextmenu', me.onDesktopMenu, me);
					},
					// ------------------------------------------------------
					// Overrideable configuration creation methods

					createDataView : function() {
						var me = this;
						return {
							xtype : 'dataview',
							overItemCls : 'x-view-over',
							itemSelector : 'div.thumb-wrap',
							trackOver : true,
							// itemSelector : me.shortcutItemSelector,
							store : me.shortcuts,
							style : {
								position : 'absolute'
							},
							x : 0,
							y : 0,
							tpl : new Ext.XTemplate(me.shortcutTpl)

						};
					},

					createDesktopMenu : function() {
						var me = this, ret = {
							items : me.contextMenuItems || []
						};

						if (ret.items.length) {
							ret.items.push('-');
						}

						var newitem = {
							text : '新建',
							scope : me,
							iconCls : 'xj',
							menu : {
								items : []
							}
						};
						newitem.menu.items.push({
							text : '快捷方式',
							handler : me.showKjfs,
							scope : me,
							iconCls : 'kjfs'
						});
						ret.items.push({
							text : '平铺',
							handler : me.tileWindows,
							scope : me,
							minWindows : 1,
							iconCls : 'tile'
						}, {
							text : '层叠',
							handler : me.cascadeWindows,
							scope : me,
							minWindows : 1,
							iconCls : 'stack-up'
						}, newitem);

						return ret;
					},
					showKjfs : function() {
						Desktop.openWindow('com.hh.usersystem.menu.ZmtbEdit', {
							title : '新建快捷方式',
							iconCls : 'kjfs',
							icon : null,
							desktopStore:myDesktopApp.desktop.shortcuts
						});
					},
					createWindowMenu : function() {
						var me = this;
						return {
							defaultAlign : 'br-tr',
							items : [ {
								text : '恢复',
								handler : me.onWindowMenuRestore,
								scope : me,
								iconCls : 'huifu'
							}, {
								text : '最小化',
								handler : me.onWindowMenuMinimize,
								scope : me,
								iconCls : 'min'
							}, {
								text : '最大化',
								handler : me.onWindowMenuMaximize,
								scope : me,
								iconCls : 'max'
							}, '-', {
								text : '关闭',
								handler : me.onWindowMenuClose,
								scope : me,
								iconCls : 'delete'
							} ],
							listeners : {
								beforeshow : me.onWindowMenuBeforeShow,
								hide : me.onWindowMenuHide,
								scope : me
							}
						};
					},

					// ------------------------------------------------------
					// Event handler methods

					onDesktopMenu : function(e) {
						var me = this, menu = me.contextMenu;
						e.stopEvent();
						if (!menu.rendered) {
							menu.on('beforeshow', me.onDesktopMenuBeforeShow,
									me);
						}
						menu.showAt(e.getXY());
						menu.doConstrain();
					},

					onDesktopMenuBeforeShow : function(menu) {
						var me = this, count = me.windows.getCount();

						menu.items.each(function(item) {
							var min = item.minWindows || 0;
							item.setDisabled(count < min);
						});
					},

					onShortcutItemClick : function(dataView, record) {
						var data = {};
						data.vsj = record.data.vsj;
						data.id = record.data.id;
						data.text = record.data.text;
						data.icon = record.data.icon;
						Ext.apply(data, record.data);
						Menu.newWindow(data);
					},

					onWindowClose : function(win) {
						var me = this;
						me.windows.remove(win);
						me.taskbar.removeTaskButton(win.taskButton);
						me.updateActiveWindow();
					},

					// ------------------------------------------------------
					// Window context menu handlers

					onWindowMenuBeforeShow : function(menu) {
						var items = menu.items.items, win = menu.theWin;
						items[0].setDisabled(win.maximized !== true
								&& win.hidden !== true); // Restore
						items[1].setDisabled(win.minimized === true); // Minimize
						items[2].setDisabled(win.maximized === true
								|| win.hidden === true); // Maximize
					},

					onWindowMenuClose : function() {
						var me = this, win = me.windowMenu.theWin;

						win.close();
					},

					onWindowMenuHide : function(menu) {
						menu.theWin = null;
					},

					onWindowMenuMaximize : function() {
						var me = this, win = me.windowMenu.theWin;

						win.maximize();
						win.toFront();
					},

					onWindowMenuMinimize : function() {
						var me = this, win = me.windowMenu.theWin;

						win.minimize();
					},

					onWindowMenuRestore : function() {
						var me = this, win = me.windowMenu.theWin;

						me.restoreWindow(win);
					},

					// ------------------------------------------------------
					// Dynamic (re)configuration methods

					getWallpaper : function() {
						return this.wallpaper.wallpaper;
					},

					setTickSize : function(xTickSize, yTickSize) {
						var me = this, xt = me.xTickSize = xTickSize, yt = me.yTickSize = (arguments.length > 1) ? yTickSize
								: xt;

						me.windows.each(function(win) {
							var dd = win.dd, resizer = win.resizer;
							dd.xTickSize = xt;
							dd.yTickSize = yt;
							resizer.widthIncrement = xt;
							resizer.heightIncrement = yt;
						});
					},

					setWallpaper : function(wallpaper, stretch) {
						// this.wallpaper.setWallpaper(wallpaper, stretch);
						this.wallpaper.setWallpaper(wallpaper, true);
						return this;
					},

					// ------------------------------------------------------
					// Window management methods

					cascadeWindows : function() {
						var x = 0, y = 0, zmgr = this.getDesktopZIndexManager();

						zmgr.eachBottomUp(function(win) {
							if (win.isWindow && win.isVisible()
									&& !win.maximized) {
								win.setPosition(x, y);
								x += 20;
								y += 20;
							}
						});
					},

					createWindow : function(config, cls) {
						var me = this, win, cfg = Ext.applyIf(config || {}, {
							stateful : false,
							isWindow : true,
							constrainHeader : true,
							minimizable : true,
							maximizable : true
						});

						cls = cls || Ext.window.Window;
						win = me.add(new cls(cfg));

						me.windows.add(win);

						win.taskButton = me.taskbar.addTaskButton(win);
						win.animateTarget = win.taskButton.el;

						win.on({
							activate : me.updateActiveWindow,
							beforeshow : me.updateActiveWindow,
							deactivate : me.updateActiveWindow,
							minimize : me.minimizeWindow,
							destroy : me.onWindowClose,
							scope : me
						});

						win.on({
							boxready : function() {
								win.dd.xTickSize = me.xTickSize;
								win.dd.yTickSize = me.yTickSize;

								if (win.resizer) {
									win.resizer.widthIncrement = me.xTickSize;
									win.resizer.heightIncrement = me.yTickSize;
								}
							},
							single : true
						});

						// replace normal window close w/fadeOut animation:
						win.doClose = function() {
							win.doClose = Ext.emptyFn; // dblclick can call
							// again...
							win.el.disableShadow();
							win.el.fadeOut({
								listeners : {
									afteranimate : function() {
										win.destroy();
									}
								}
							});
						};

						return win;
					},

					getActiveWindow : function() {
						var win = null, zmgr = this.getDesktopZIndexManager();

						if (zmgr) {
							// We cannot rely on activate/deactive because that
							// fires against non-Window
							// components in the stack.

							zmgr.eachTopDown(function(comp) {
								if (comp.isWindow && !comp.hidden) {
									win = comp;
									return false;
								}
								return true;
							});
						}

						return win;
					},

					getDesktopZIndexManager : function() {
						var windows = this.windows;
						// TODO - there has to be a better way to get this...
						return (windows.getCount() && windows.getAt(0).zIndexManager)
								|| null;
					},

					getWindow : function(id) {
						return this.windows.get(id);
					},

					minimizeWindow : function(win) {
						win.minimized = true;
						win.hide();
					},

					restoreWindow : function(win) {
						if (win.isVisible()) {
							win.restore();
							win.toFront();
						} else {
							win.show();
						}
						return win;
					},

					tileWindows : function() {
						var me = this, availWidth = me.body.getWidth(true);
						var x = me.xTickSize, y = me.yTickSize, nextY = y;

						me.windows.each(function(win) {
							if (win.isVisible() && !win.maximized) {
								var w = win.el.getWidth();

								// Wrap to next row if we are not at the line
								// start and this Window will
								// go off the end
								if (x > me.xTickSize && x + w > availWidth) {
									x = me.xTickSize;
									y = nextY;
								}

								win.setPosition(x, y);
								x += w + me.xTickSize;
								nextY = Math.max(nextY, y + win.el.getHeight()
										+ me.yTickSize);
							}
						});
					},

					updateActiveWindow : function() {
						var me = this, activeWindow = me.getActiveWindow(), last = me.lastActiveWindow;
						if (activeWindow === last) {
							return;
						}

						if (last) {
							if (last.el.dom) {
								last.addCls(me.inactiveWindowCls);
								last.removeCls(me.activeWindowCls);
							}
							last.active = false;
						}

						me.lastActiveWindow = activeWindow;

						if (activeWindow) {
							activeWindow.addCls(me.activeWindowCls);
							activeWindow.removeCls(me.inactiveWindowCls);
							activeWindow.minimized = false;
							activeWindow.active = true;
						}

						me.taskbar.setActiveButton(activeWindow
								&& activeWindow.taskButton);
					}
				});
